package com.zaizai.zaizai_good.interceptor;
import com.zaizai.zaizai_good.utils.BaseContext;
import com.zaizai.zaizai_good.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * jwt令牌校验的拦截器
 */
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、从请求头中获取令牌
        String token = request.getHeader("Authorization");

        //2、校验令牌
        try {
            Claims claims = JwtUtil.parseJWT("zaizai", token);
            if (claims==null){
                //token已经失效了
                throw new RuntimeException();
            }
            Long userId = Long.valueOf(claims.get("id").toString());
            //将一次用户请求的线程创建出来，并将用户的id存储
            BaseContext.setCurrentId(userId);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
